package com.changgou.interceptor;

import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 老大哥在看着你
 *
 * @author ANG.YU
 * @date 2019-10-22 23:08
 */
public class FeignInterceptor implements feign.RequestInterceptor {
    public static final String AUTHORIZATION = "Authorization";
    //微服务之间的令牌传递
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if(null != servletRequestAttributes){
            //本微服务请求
            HttpServletRequest request = servletRequestAttributes.getRequest();

            Enumeration<String> headerNames = request.getHeaderNames();
            if(null != headerNames){
                while (headerNames.hasMoreElements()){
                    String key = headerNames.nextElement();
                    String value = request.getHeader(key);
                    if(key.equalsIgnoreCase(AUTHORIZATION)){
                        requestTemplate.header(key,value);
                    }
                }
            }
        }
    }
}
